import axios from 'axios'
import { django_path } from '@/mylibs/define'

// axios.defaults.baseURL = '/api'
axios.defaults.baseURL = django_path

// 判断是否登录
export function is_signin(fun_back) {
  axios({ url: 'blogs/api/is_signin/', method: 'post', withCredentials: true })
    .then((response) => {
      console.log(response)
      if (fun_back) {
        fun_back(response)
      }
    })
    .catch(function (error) {
      // 请求失败处理
      console.log(error)
    })
}

// 登录
export async function signin(username, password, fun_back) {
  var result = {
    ok: true,
    err: ''
  }
  var upload = {
    username: username,
    password: password
  }

  var { data: res } = await axios({
    url: 'blogs/api/signin/',
    method: 'post',
    data: upload,
    withCredentials: true // 允许携带cookie
  }).catch(function (error) {
    // 请求失败处理
    console.log(error)
    result.ok = false
    result.err = error
  })
  if (res)
    if (res.ret != 0) {
      result.ok = false
      result.err = res.msg
    }
  return result
}

// 退出登录
export function signout(fun_back) {
  axios({
    url: 'blogs/api/signout/',
    method: 'post',
    withCredentials: true
  }).then((res) => {
    if (fun_back) {
      fun_back(res)
    }
  })
}

// 修改密码
export function remake_password(user, oldpass, newpass, fun_back) {
  var data = {
    username: user,
    password: oldpass,
    new_password: newpass
  }
  axios({
    url: 'blogs/api/remake_password/',
    method: 'post',
    data,
    withCredentials: true
  }).then((res) => {
    if (fun_back) {
      fun_back(res)
    }
  })
}
